package top.lywivan.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.Constants;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.SecurityContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
@Component
public class LoginCheckFilter implements Filter {
    //用于进行正则匹配
    private AntPathMatcher antPathMatcher=new AntPathMatcher();
    /**
     * 用于完善登陆功能，验证登陆信息
     * @param servletRequest 获取uri和session对象
     * @param servletResponse 响应全段信息
     * @param filterChain 放行过滤器
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        //log.info("用户请求的uri为：{}",uri);
        /*if ("/front".equals(uri)||"/front/".equals(uri)){
            resp.sendRedirect("/front/index.html");
            return;
        }
        if ("/backend".equals(uri)||"/backend/".equals(uri)){
            resp.sendRedirect("/backend/index.html");
            return;
        }*/
        //判断是否是登陆相关内容，然后直接进行放行
        if (checkAccess(uri)){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        Long employeeId = (Long) req.getSession().getAttribute(Constants.EMPLOYEE_ID_SESSION_KEY);
        Long userId = (Long) req.getSession().getAttribute(Constants.USER_ID_SESSION_KEY);
        if (employeeId!=null||userId!=null){
            //将当前登陆的用户id存入ThreadLocal，用于公共字段的自动填充
            if (employeeId!=null){
                SecurityContext.setUserId(employeeId);
            }else {
                SecurityContext.setUserId(userId);
            }
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        /*String referer = req.getHeader("Referer");
        if (employeeId!=null&&referer.contains("backend")){
            SecurityContext.setUserId(employeeId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if (userId!=null&&referer.contains("front")){
            SecurityContext.setUserId(userId);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }*/
        R<Object> error = R.error("NOTLOGIN");
        resp.getWriter().print(JSON.toJSONString(error));
    }

    /**
     * 判断是否是登陆相关内容
     * @param uri 用户请求的uri
     * @return
     */
    private boolean checkAccess(String uri) {
        String[] accesses={
            "/employee/login",
            "/employee/logout",
            /*"/backend/api/**",
            "/backend/images/**",
            "/backend/js/**",
            "/backend/page/**",
            "/backend/plugins/**",
            "/backend/styles/**",
            "/backend/favicon.ico",
            "/backend/index.html",*/
            "/backend/**",
            "/front/**",
            "/user/sendMsg",
            "/user/login"
            //    ,"/dish/list"
            /*    ,"/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"*/
        };
        for (String access : accesses) {
            boolean match = antPathMatcher.match(access, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
